﻿using ALProtocol.Tcp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Demo
{
    /// <summary>
    /// 客户端的演示类。
    /// </summary>
    internal class TcpClientDemo
    {
        /// <summary>
        /// 服务端的实例。
        /// </summary>
        private TcpClient m_client;
        private DemoSession m_session = null; // 建立的会话。
        private readonly object m_sessionLocker = new object(); // 会话的锁。
        private IPEndPoint m_remoteEndPoint = null;// 远端节点。
        /// <summary>
        /// 
        /// </summary>
        public TcpClientDemo()
        {
            m_client = new TcpClient();
            m_client.SessionChanged += OnSessionChanged;
        }

        /// <summary>
        /// 启动。
        /// </summary>
        /// <param name="address"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        public bool Start(IPAddress address, int port)
        {
            m_remoteEndPoint = new IPEndPoint(address, port);
           return m_client.Connect(m_remoteEndPoint);
        }
        /// <summary>
        /// 推送消息。
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool PushMsg(string msg) 
            => m_session.WriteData(msg); 

        private void OnSessionChanged(TcpSession session, bool connected)
        {
            lock (m_sessionLocker)
            {
                if(connected)
                {
                    Console.WriteLine($"链接会话（端口：{session.Local.Port}）");
                    m_session = new DemoSession(session);
                    m_session.WriteData($"我是客户端{session.Local.Port}！");  
                }
                else
                {
                    Console.WriteLine($"链接会话断开（端口：{session.Local.Port}）");
                    m_session = null;
                    m_client.Reset();
                    m_client.Connect(m_remoteEndPoint);
                }
            }
        }
    }
}
